<template>
  <div class="add-fee-page">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑费用记录' : (isView ? '查看费用记录' : '新增费用记录') }}</h2>
      <button @click="goBack" class="back-btn"> 返回</button>
    </div>
    
    <div class="fee-form-container">
      <form @submit.prevent="handleSubmit" class="fee-form">
        <!-- 外协单位 -->
        <div class="form-group">
          <label class="required">*货主单位:</label>
          <input
            type="text"
            v-model="formData.consignorUnit"
            placeholder="请输入外协单位"
            class="form-input"
            :class="{ error: errors.consignorUnit }"
            :readonly="isView"
          />
          <span v-if="errors.consignorUnit" class="error-message">{{ errors.consignorUnit }}</span>
        </div>

        <!-- 结算方式 -->
        <div class="form-group">
          <label class="required">*结算方式:</label>
          <div class="radio-group">
            <label v-for="method in paymentMethods" :key="method.value" class="radio-item">
              <input
                type="radio"
                :value="method.value"
                v-model="formData.paymentMethod"
                @change="handlePaymentMethodChange"
                class="radio-input"
                :disabled="isView"
              />
              <span class="radio-label">{{ method.label }}</span>
            </label>
            <div v-if="formData.paymentMethod === '其它'" class="other-input-wrapper">
              <input
                type="text"
                v-model="formData.otherPaymentMethod"
                placeholder="请输入其他支付方式"
                class="form-input other-input"
                :class="{ error: errors.otherPaymentMethod }"
                :readonly="isView"
              />
            </div>
          </div>
          <span v-if="errors.paymentMethod" class="error-message">{{ errors.paymentMethod }}</span>
        </div>

        <!-- 吨位 -->
        <div class="form-group">
          <label class="required">*吨位(立方米):</label>
          <input
            type="number"
            v-model="formData.tonnage"
            placeholder="请输入吨位"
            class="form-input"
            :class="{ error: errors.tonnage }"
            step="0.01"
            min="0"
            :readonly="isView"
          />
          <span v-if="errors.tonnage" class="error-message">{{ errors.tonnage }}</span>
        </div>

        <!-- 单价 -->
        <div class="form-group">
          <label class="required">*单价(元/立方米):</label>
          <input
            type="number"
            v-model="formData.unitPrice"
            placeholder="请输入单价"
            class="form-input"
            :class="{ error: errors.unitPrice }"
            step="0.01"
            min="0"
            @input="calculateAmount"
            :readonly="isView"
          />
          <span v-if="errors.unitPrice" class="error-message">{{ errors.unitPrice }}</span>
        </div>

        <!-- 金额 -->
        <div class="form-group">
          <label class="required">*金额:</label>
          <input
            type="number"
            v-model="formData.amount"
            placeholder="请输入金额"
            class="form-input"
            :class="{ error: errors.amount }"
            step="0.01"
            min="0"
            @input="handleAmountChange"
            :readonly="isView"
          />
          <span v-if="errors.amount" class="error-message">{{ errors.amount }}</span>
        </div>

        <!-- 业务日期 -->
        <div class="form-group">
          <label class="required">*业务日期:</label>
          <div class="date-input-wrapper">
            <input
              type="date"
              v-model="formData.businessDate"
              placeholder="请选择业务日期"
              class="form-input date-input"
              :class="{ error: errors.businessDate }"
              :readonly="isView"
            />
            <i class="icon-calendar"></i>
          </div>
          <span v-if="errors.businessDate" class="error-message">{{ errors.businessDate }}</span>
        </div>

        <!-- 经办人 -->
        <div class="form-group">
          <label class="required">*经办人:</label>
          <input
            type="text"
            v-model="formData.handler"
            placeholder="请输入经办人"
            class="form-input"
            :class="{ error: errors.handler }"
            :readonly="isView"
          />
          <span v-if="errors.handler" class="error-message">{{ errors.handler }}</span>
        </div>

        <!-- 备注 -->
        <div class="form-group">
          <label class="required">*备注:</label>
          <textarea
            v-model="formData.notes"
            placeholder="请输入备注信息"
            class="form-textarea"
            :class="{ error: errors.notes }"
            rows="3"
            :readonly="isView"
          ></textarea>
          <span v-if="errors.notes" class="error-message">{{ errors.notes }}</span>
        </div>

        <!-- 按钮组 -->
        <div class="form-actions" v-if="!isView">
          <button type="button" @click="goBack" class="btn btn-cancel">
            取消
          </button>
          <button type="submit" class="btn btn-submit" :disabled="loading">
            {{ loading ? '提交中...' : '提交' }}
          </button>
        </div>
        
        <!-- 查看模式按钮组 -->
        <div class="form-actions" v-if="isView">
          <button type="button" @click="goBack" class="btn btn-cancel">
            返回
          </button>
          <button type="button" @click="handleEdit" class="btn btn-edit">
            编辑
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { feeApi } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

// 接口定义 - 根据API接口调整
interface FeeFormData {
  consignorUnit: string
  paymentMethod: string
  otherPaymentMethod: string
  tonnage: number | string
  unitPrice: number | string
  amount: number | string
  businessDate: string
  handler: string
  notes: string
  businessOrderNo: string
}

// 添加这个接口定义
interface FeeFormErrors {
  consignorUnit?: string
  paymentMethod?: string
  otherPaymentMethod?: string
  tonnage?: string
  unitPrice?: string
  amount?: string
  businessDate?: string
  handler?: string
  notes?: string  // 添加notes字段
}

// API请求接口 - 使用notes字段
interface FeeSubmitData {
  id: number
  businessOrderNo: string
  consignorUnit: string
  paymentMethod: string
  tonnage: number
  unitPrice: number
  amount: number
  businessDate: string
  handler: string
  notes: string  // 使用notes
  processDetailCode: string
  payfee: boolean
  createdTime: string
}

// API响应接口
interface FeeDetailResponse {
  code: number
  message: string
  data: {
    id: number
    businessOrderNo: string
    consignorUnit: string
    paymentMethod: string
    tonnage: number
    unitPrice: number
    amount: number
    businessDate: string
    handler: string
    notes: string
    approvalStatus: number
    approvalByName: string | null
    approvalTime: string | null
    createdTime: string
    payFee: boolean
  }
}

// 路由
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const isEdit = ref(false)
const isView = ref(false)
const currentId = ref<number | null>(null)

// 表单数据
const formData = reactive<FeeFormData>({
  consignorUnit: '',
  paymentMethod: '',
  otherPaymentMethod: '',
  tonnage: '',
  unitPrice: '',
  amount: '',
  businessDate: '',
  handler: '',
  notes: '',
  businessOrderNo: ''
})

// 表单错误
const errors = reactive<FeeFormErrors>({})

// 结算方式选项
const paymentMethods = [
  { value: '微信支付', label: '微信支付' },
  { value: '支付宝支付', label: '支付宝支付' },
  { value: '银联支付', label: '银联支付' },
  { value: '企业转账', label: '企业转账' },
  { value: '线下支付', label: '线下支付' },
  { value: '银行转账', label: '银行转账' },
  { value: '其它', label: '其它' }
]

// 计算属性
const isOtherPayment = computed(() => formData.paymentMethod === '其它')

// 生命周期
onMounted(() => {
  // 检查路由参数和查询参数
  const id = route.params.id
  const mode = route.query.mode as string
  
  console.log('接收到的路由参数:', { 
    id, 
    mode, 
    params: route.params, 
    query: route.query 
  })
  
  // 验证ID参数 - 更宽松的验证
  if (!id) {
    console.error('未找到ID参数')
    showError('未找到记录ID')
    router.back()
    return
  }
  
  const numericId = Number(id)
  if (isNaN(numericId)) {
    console.error('ID不是有效数字:', id)
    showError('记录ID格式无效')
    router.back()
    return
  }
  
  currentId.value = numericId
  if (mode === 'view') {
    isView.value = true
  } else {
    isEdit.value = true
  }
  
  // 加载数据
  loadEditData(numericId)
})

// 加载编辑/查看数据
const loadEditData = async (id: number) => {
  try {
    loading.value = true
    console.log('加载费用详情，ID:', id)
    
    const response = await feeApi.getReceivableFeeDetails(id)
    
    console.log('API响应:', response)
    
    if (response.code === 200) {
      const data = response.data
      
      // 填充表单数据 - 注意字段映射
      formData.businessOrderNo = data.businessOrderNo || ''
      formData.consignorUnit = data.consignorUnit || ''
      formData.paymentMethod = data.paymentMethod || ''
      formData.otherPaymentMethod = data.paymentMethod === '其它' ? data.paymentMethod : ''
      formData.tonnage = data.tonnage || ''
      formData.unitPrice = data.unitPrice || ''
      formData.amount = data.amount || ''
      formData.businessDate = data.businessDate ? data.businessDate.split('T')[0] : ''
      formData.handler = data.handler || ''
      formData.notes = data.notes || '' // 注意：这里保持notes，因为表单中使用的是notes
      
      console.log('数据加载成功:', formData)
    } else {
      showError(`加载数据失败: ${response.message}`)
    }
  } catch (error: any) {
    console.error('加载数据失败:', error)
    showError('加载数据失败，请检查网络连接或联系管理员')
  } finally {
    loading.value = false
  }
}

// 编辑功能
const handleEdit = () => {
  isView.value = false
  isEdit.value = true
}

// 方法
const resetForm = () => {
  Object.assign(formData, {
    consignorUnit: '',
    paymentMethod: '',
    otherPaymentMethod: '',
    tonnage: '',
    unitPrice: '',
    amount: '',
    businessDate: '',
    handler: '',
    notes: '',
    businessOrderNo: ''
  })
  clearErrors()
}

const clearErrors = () => {
  Object.keys(errors).forEach(key => {
    delete errors[key as keyof FeeFormErrors]
  })
}

const validateForm = (): boolean => {
  clearErrors()
  let isValid = true

  // 验证外协单位
  if (!formData.consignorUnit.trim()) {
    errors.consignorUnit = '请输入外协单位'
    isValid = false
  }

  // 验证结算方式
  if (!formData.paymentMethod) {
    errors.paymentMethod = '请选择结算方式'
    isValid = false
  } else if (formData.paymentMethod === '其它' && !formData.otherPaymentMethod.trim()) {
    errors.otherPaymentMethod = '请输入其他支付方式'
    isValid = false
  }

  // 验证吨位
  const tonnage = Number(formData.tonnage)
  if (!formData.tonnage || isNaN(tonnage) || tonnage <= 0) {
    errors.tonnage = '请输入有效的吨位（大于0的数字）'
    isValid = false
  }

  // 验证单价
  const unitPrice = Number(formData.unitPrice)
  if (!formData.unitPrice || isNaN(unitPrice) || unitPrice <= 0) {
    errors.unitPrice = '请输入有效的单价（大于0的数字）'
    isValid = false
  }

  // 验证金额
  const amount = Number(formData.amount)
  if (!formData.amount || isNaN(amount) || amount <= 0) {
    errors.amount = '请输入有效的金额（大于0的数字）'
    isValid = false
  }

  // 验证业务日期
  if (!formData.businessDate) {
    errors.businessDate = '请选择业务日期'
    isValid = false
  }

  // 验证经办人
  if (!formData.handler.trim()) {
    errors.handler = '请输入经办人'
    isValid = false
  }

  // 验证备注 - 添加必填验证
  if (!formData.notes.trim()) {
    errors.notes = '请输入备注信息'
    isValid = false
  }

  return isValid
}

const calculateAmount = () => {
  if (isView.value) return
  
  const tonnage = Number(formData.tonnage)
  const unitPrice = Number(formData.unitPrice)
  
  if (tonnage > 0 && unitPrice > 0) {
    formData.amount = (tonnage * unitPrice).toFixed(2)
  }
}

const handleAmountChange = () => {
  if (isView.value) return
  
  const tonnage = Number(formData.tonnage)
  const amount = Number(formData.amount)
  
  if (tonnage > 0 && amount > 0) {
    formData.unitPrice = (amount / tonnage).toFixed(2)
  }
}

const handlePaymentMethodChange = () => {
  if (isView.value) return
  
  if (formData.paymentMethod !== '其它') {
    formData.otherPaymentMethod = ''
  }
}

// 生成业务单号
const generateBusinessOrderNo = (): string => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `FE${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 消息提示方法
const showSuccess = (message: string) => {
  ElMessage.success({
    message,
    duration: 3000,
    showClose: true
  })
}

const showError = (message: string) => {
  ElMessage.error({
    message,
    duration: 5000,
    showClose: true
  })
}

const showWarning = (message: string) => {
  ElMessage.warning({
    message,
    duration: 4000,
    showClose: true
  })
}

const handleSubmit = async () => {
  if (isView.value) return
  
  if (!validateForm()) {
    showWarning('请检查表单填写是否完整')
    return
  }

  loading.value = true
  
  try {
    // 直接使用notes字段，不要note
    const submitData = {
      id: isEdit.value ? currentId.value : 0,
      businessOrderNo: isEdit.value ? formData.businessOrderNo : generateBusinessOrderNo(),
      consignorUnit: formData.consignorUnit.trim(),
      paymentMethod: formData.paymentMethod === '其它' ? formData.otherPaymentMethod.trim() : formData.paymentMethod,
      tonnage: Number(formData.tonnage),
      unitPrice: Number(formData.unitPrice),
      amount: Number(formData.amount),
      businessDate: formData.businessDate + 'T00:00:00.000Z',
      handler: formData.handler.trim(),
      notes: formData.notes.trim() || '无备注', // 改为notes
      processDetailCode: '',
      payfee: false,
      createdTime: new Date().toISOString()
    }
    
    console.log('提交数据:', submitData)
    
    const response = isEdit.value 
      ? await feeApi.updateReceivableFee(submitData)
      : await feeApi.addReceivableFee(submitData)
    
    if (response.code === 200) {
      showSuccess(isEdit.value ? '费用记录更新成功！' : '费用记录添加成功！')
      setTimeout(() => {
        goBack()
      }, 1500)
    } else {
      showError(`${isEdit.value ? '更新' : '添加'}失败：${response.message}`)
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    showError('提交失败，请检查数据格式')
  } finally {
    loading.value = false
  }
}

const goBack = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要离开吗？未保存的数据将丢失。',
      '确认离开',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    router.back()
  } catch {
    // 用户取消离开
  }
}
</script>

<style scoped>
.add-fee-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 800px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.back-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.back-btn:hover {
  background: #40a9ff;
}

.fee-form-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 24px;
  width: 100%;
  max-width: 800px;
}

.fee-form {
  max-width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-group label.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus, .form-textarea:focus {
  border-color: #1890ff;
}

.form-input.error, .form-textarea.error {
  border-color: #ff4d4f;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 8px;
}

.radio-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin: 0;
}

.radio-input {
  margin-right: 8px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.radio-label {
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.other-input-wrapper {
  margin-top: 12px;
  width: 100%;
}

.other-input {
  width: 100%;
}

.date-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.date-input {
  padding-right: 40px;
}

.icon-calendar {
  position: absolute;
  right: 12px;
  color: #999;
  font-size: 16px;
  pointer-events: none;
}

.error-message {
  display: block;
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.btn {
  padding: 10px 24px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 80px;
}

.btn-cancel {
  background-color: white;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.btn-cancel:hover {
  background-color: #e6f7ff;
  border-color: #40a9ff;
}

.btn-submit {
  background-color: #1890ff;
  color: white;
}

.btn-submit:hover:not(:disabled) {
  background-color: #40a9ff;
}

.btn-submit:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 查看模式样式 */
.form-input[readonly],
.form-textarea[readonly] {
  background-color: #f5f5f5;
  color: #666;
  cursor: not-allowed;
}

.radio-input:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.btn-edit {
  background-color: #52c41a;
  color: white;
}

.btn-edit:hover {
  background-color: #73d13d;
}

/* Toast 消息提示样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  color: white;
  font-weight: 500;
  font-size: 14px;
  z-index: 9999;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 300px;
  word-wrap: break-word;
}

.toast.show {
  transform: translateX(0);
}

.toast-success {
  background: #52c41a;
}

.toast-error {
  background: #ff4d4f;
}

.toast-warning {
  background: #faad14;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-fee-page {
    padding: 10px;
    max-width: 100%;
  }
  
  .page-header {
    max-width: 100%;
  }
  
  .fee-form-container {
    padding: 16px;
    max-width: 100%;
  }
  
  .radio-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }

  .toast {
    right: 10px;
    left: 10px;
    max-width: none;
    transform: translateY(-100%);
  }
  
  .toast.show {
    transform: translateY(0);
  }
}
</style>

